import myConfirm from '../components/myConfirm'

function Confirm () {
    return Confirm
}

// 定义插件的install方法
Confirm.install = (function () {
    let Vue
    // 将组建实例化
    return function (_Vue) {
        if (Vue === _Vue) {
            return
        }
        const createConfirm = _Vue.extend(myConfirm)
        let currentConfirm;
        function initConfirm () {
            currentConfirm = new createConfirm()
            let tempConfirm = currentConfirm.$mount().$el
            document.body.appendChild(tempConfirm)
        }
        // myConfirm 方法 挂载到_Vue实例上可在组件中通过this.$myConfirm调用
        _Vue.prototype.$myConfirm = {
            show (options) {
                // 判断弹窗是否初始化
                if (!currentConfirm) initConfirm()
                if (typeof options === 'string') {
                    currentConfirm.content = options;
                } else {
                    Object.assign(currentConfirm, options);
                }
                // 返回promise对象可在调用时通过async阻断后续代码
                return currentConfirm.showConfirm()
                    .then(val => {
                        currentConfirm = null
                        return val
                    })
                    .catch(err => {
                        currentConfirm = null
                        return err
                    })
            }
        }
        Vue = _Vue
    }
})()

export default Confirm